//
//  CommutationSwitchOnlineStatusViewController.swift
//  AlterationSwitch
//
//  Created by solarke_apple_mini_1 on 2018/10/25.
//  Copyright © 2018年 石家庄科林电气股份有限公司. All rights reserved.
//

import UIKit

class CommutationSwitchOnlineStatusViewController: BaseViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    // MARK: - Properties
    var pileCode :String!
    var objects = [AnyObject]()
    
    // MARK: - IBOutlet
    @IBOutlet var collection:UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        notificationCenter.addObserver(self, selector: #selector(dealWithSwitchOnlineData(sender:)), name: CommutationSwitchOnlineNotification, object: nil)
    }
    
    @IBAction func queryButtonTap() {
        query()
    }
    
    func query() {
        let termaddr:UnsafeMutablePointer<UInt8> = getTermaddr()
        let askOneData_fn15_send = ocFile().askOneData_fn15_send(termaddr, a3: a3)
        var arr = [UInt8](repeating: 0, count: 37)
        //将dst中的所有元素拷贝到arr中
        for i in 0..<37 {
            arr[i] = UInt8(askOneData_fn15_send[i])
        }
        sendMessageBytes(msg: arr)
        showLoading(true)
    }
    
    @objc func dealWithSwitchOnlineData(sender: NSNotification) {
        let info = sender.userInfo as! [String: AnyObject]
        let data = info["data"] as AnyObject
        objects = data as! [AnyObject]
        collection.reloadData()
        showLoading(false)
    }
    
    //加载cell数据
    func loadForCell(cell: TwoCollectionCell, atIndex index: Int, withObject object: AnyObject) {
        var int = object.object(forKey: "kg") as! Int
        cell.numLabel.text = String(int)
        
        int = object.object(forKey: "status") as! Int
        if int == 0 {
            cell.backView.backgroundColor = UIColor.lightGray
        } else {
            cell.backView.backgroundColor = mainColor
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return objects.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TwoCollectionCell
        let object = objects[indexPath.row]
        loadForCell(cell: cell, atIndex: indexPath.row, withObject: object)
        return cell
    }
    
    // MARK: - UICollectionViewDelegateFlowLayout
    //cell宽、高
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let wid = (windowSize.width-50)/4
        let size = CGSize(width: wid, height: wid/2)
        return size
    }
}

class TwoCollectionCell: UICollectionViewCell {
    @IBOutlet weak var backView: UIView!
    @IBOutlet weak var numLabel: UILabel!
}
